//
//  SearchViewController.m
//  JianChaRiBao
//
//  Created by Changxy on 13-6-7.
//  Copyright (c) 2013年 wzyk. All rights reserved.
//

#import "SearchViewController.h"
#import "NovelCell.h"
#import "MagazineInfoViewController.h"
#import "ListenInfoViewController.h"
#import "NovelInfoViewController.h"

#import "AppDelegate.h"
@interface SearchViewController ()

@end

@implementation SearchViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}
- (IBAction)backBtn:(id)sender {
    [self.navigationController popToRootViewControllerAnimated: YES];
}
-(void)searchBarCancelButtonClicked:(UISearchBar *)searchBar{
    [searchBar resignFirstResponder];
}
-(BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar{
    [mSearchBar setShowsCancelButton:YES animated:YES];
    [self.view bringSubviewToFront:backView];
    [UIView animateWithDuration:0.3 animations:^{
        backView.hidden = NO;
        backView.alpha = 0.6;
    }];
    return YES;
}
-(BOOL)searchBarShouldEndEditing:(UISearchBar *)searchBar{
    [mSearchBar setShowsCancelButton:NO animated:YES];
    [searchBar resignFirstResponder];
    [UIView animateWithDuration:0.3 animations:^{
        backView.alpha = 0.0;
    } completion:^(BOOL finished) {
        backView.hidden = YES;
    }];
    return YES;
}
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    UITouch * touch = [touches anyObject];
    if (touch.view == backView) {
        [mSearchBar resignFirstResponder];
    }
}
-(void)addDataWithObj:(id)obj{
    if (obj && [obj isKindOfClass:[NSDictionary class]]) {
        NSArray * array = [obj objectForKey:@"result"];
        if (array && array.count != 0) {
            SearchView.hidden = NO;
            [mDataArray addObjectsFromArray:array];
            [SearchView reloadData];
        }else{
            ABPromptView * abp = [[[ABPromptView alloc]initWithTitle:@"找不到相关搜索结果"]autorelease];
            [abp show];
            SearchView.hidden = YES;
        }
    }
}
    
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{
    
    [searchBar resignFirstResponder];
    [mDataArray removeAllObjects];
    [self showLoadingView];
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        id obj = nil;
        switch (self.type) {
            case searchMagzine:
               obj  = [[DataRequest sharedRequest] getSearchInfo:searchBar.text];
                break;
            case searchListen:
                obj = [[DataRequest sharedRequest] getListenSearchResult:searchBar.text];
                break;
            case searchNovel:
                obj = [[DataRequest sharedRequest] getNovelSearchResult:searchBar.text];
                break;
            default:
                break;
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            [self removeloadingView];
            [self addDataWithObj:obj];
        });

    });
}
-(NSUInteger)numberOfItemsInGridView:(AQGridView *)gridView{
    return mDataArray.count;
}
-(AQGridViewCell *)gridView:(AQGridView *)gridView cellForItemAtIndex:(NSUInteger)index{
        static NSString *CellIdentify = @"cellID";
        NovelCell * cell = (NovelCell *)[gridView dequeueReusableCellWithIdentifier:CellIdentify];
        if (cell == nil) {
            cell = [[NovelCell alloc]initWithFrame:CGRectMake(0, 0, 70, 100) reuseIdentifier:CellIdentify];
        }
        cell.novelInfo = [mDataArray objectAtIndex:index];
        
        [cell updateDisplayWithImageStr:@"image"];
        
        return cell;
        
}
-(CGSize)portraitGridCellSizeForGridView:(AQGridView *)gridView{
    return CGSizeMake(80, 150);
}
- (CGRect)gridView:(AQGridView *)gridView adjustCellFrame:(CGRect)cellFrame withinGridCellFrame:(CGRect)gridCellFrame
{
    cellFrame.origin.y -= 5;
    return cellFrame;
}
-(void)gridView:(AQGridView *)gridView didSelectItemAtIndex:(NSUInteger)index{
    switch (self.type) {
        case searchMagzine:
        {
            MagazineInfoViewController * magazineInfoViewController = [[MagazineInfoViewController alloc]initWithNibName:@"MagazineInfoViewController" bundle:nil];
            magazineInfoViewController.basicInfo = [mDataArray objectAtIndex:index];
            [[UIApplication rootNavController] pushViewController:magazineInfoViewController animated:YES];

        }
            break;
        case searchListen:
        {
            ListenInfoViewController * listenInfoViewController = [[ListenInfoViewController alloc]initWithNibName:@"ListenInfoViewController" bundle:nil];
            listenInfoViewController.listenID = [[mDataArray objectAtIndex:index] objectForKey:@"item_id"];
            listenInfoViewController.listenName = [[mDataArray objectAtIndex:index] objectForKey:@"item_name"];
            [[UIApplication rootNavController] pushViewController:listenInfoViewController animated:YES];

        }
            break;
        case searchNovel:
        {
            NovelInfoViewController * novelInfoViewController = [[NovelInfoViewController alloc]initWithNibName:@"NovelInfoViewController" bundle:nil];
            novelInfoViewController.basicInfo = [mDataArray objectAtIndex:index];
            [[UIApplication rootNavController] pushViewController:novelInfoViewController animated:YES];

        }
            break;
        default:
            break;
    }
    [gridView deselectItemAtIndex:index animated:NO];
    
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
    shouldSwipeBack = YES;
    mDataArray = [[NSMutableArray alloc]initWithCapacity:0];
    SearchView.hidden = YES;
    UIView *bgView1 = [[UIView alloc] init];
    bgView1.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"bookshelf_cell_bg"]];
    SearchView.backgroundView = bgView1;
    SearchView.backgroundViewExtendsDown = YES;
    SearchView.leftContentInset = 20;
    SearchView.rightContentInset = 20;
    SearchView.contentInset = UIEdgeInsetsMake(0, 0, 1, 0);
    [bgView1 release];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)showLoadingView
{
    if (loadingView.superview) {
        return;
    }
    if (loadingView == nil) {
        loadingView = [[[ABSpringLoadingView alloc] initWithFrame:SearchView.frame] autorelease];
    }
    loadingView.alpha = 0;
    [self.view addSubview:loadingView];
    [UIView animateWithDuration:0.3 animations:^{
        loadingView.alpha = 1;
    }];
}

- (void)removeloadingView
{
    if (loadingView) {
        [UIView animateWithDuration:0.3 animations:^{
            loadingView.alpha = 0;
        } completion:^(BOOL finished) {
            [loadingView removeFromSuperview];
            loadingView = nil;
        }];
    }
}

- (void)dealloc {
    [mSearchBar release];
    [SearchView release];
    [backView release];
    [super dealloc];
}
- (void)viewDidUnload {
    [mSearchBar release];
    mSearchBar = nil;
    [SearchView release];
    SearchView = nil;
    [backView release];
    backView = nil;
    [super viewDidUnload];
}
@end
